<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电子时钟</title>
    <style>
        .clock{
            width: 200px;
            height: 50px;
            text-align: center;   
            line-height: 50px;
            border:solid 1px #123;
        }
    </style>
</head>
<body>
    <button>电子时钟</button>
    <button>下去吧</button>
    <hr>

    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


    <script type="text/babel">

        //声明类
        class Clock extends React.Component{
            state = {
                timeStr: ''
            }

            //组件挂载完成的生命周期回调
            componentDidMount(){
                this.timer = setInterval(() => {
                    //生成字符串
                    // let str = '2021-10-10 10:10:10';
                    this.setState({
                        timeStr: moment().format('YYYY-MM-DD HH:mm:ss')
                    })
                }, 1000);
            }

            //组件即将卸载的生命周期回调
            componentWillUnmount(){
                //停止定时器
                clearInterval(this.timer);
            }

            render(){
                console.log(11);
                return <div className="clock">{this.state.timeStr} </div>
            }
        }

        //获取所有的按钮
        let btns = document.querySelectorAll('button');

        btns[0].addEventListener('click', function(){
            ReactDOM.render(<Clock />, document.querySelector("#root"));
        })

        btns[1].addEventListener('click', function(){
            //卸载组件
            ReactDOM.unmountComponentAtNode(document.querySelector("#root"));
        });


    </script>
    
</body>
</html>